/**
 * 为了修改select在IE6下DIV无法遮盖,配合ext-all-patch.css文件中的.x-masked select, .ext-ie6 .x-masked select和.ext-ie6 .x-unmasked select使用
 * addby H2H
 */
Ext.override(Ext.Element, {
	mask : function(msg, msgCls) {
		if(this.getStyle("position") == "static"){
            this.addClass("x-masked-relative");
        }
        if(this._maskMsg){
            this._maskMsg.remove();
        }
        if(this._mask){
            this._mask.remove();
        }
		this._mask = Ext.DomHelper.append(this.dom, {cls:"ext-el-mask"}, true);

		this.removeClass("x-unmasked");

		this.addClass("x-masked");
        this._mask.setDisplayed(true);
        if(typeof msg == 'string'){
            this._maskMsg = Ext.DomHelper.append(this.dom, {cls:"ext-el-mask-msg", cn:{tag:'div'}}, true);
            var mm = this._maskMsg;
            mm.dom.className = msgCls ? "ext-el-mask-msg " + msgCls : "ext-el-mask-msg";
            mm.dom.firstChild.innerHTML = msg;
            mm.setDisplayed(true);
            mm.center(this);
        }
        if(Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
            this._mask.setSize(this.getWidth(), this.getHeight());
        }
        if (Ext.isIE6) {
        	$('select' , this.dom).attr("disabled" , true) ;
        }
        
		return this._mask
	},

	/**
     * Removes a previously applied mask.
     */
    unmask : function(){
        if(this._mask){
        	//2010-4-22 jcc 移到if(this._mask)中,避免点击层后下拉框重新可用
            if (Ext.isIE6) {
            	this.addClass("x-unmasked");
            	$('select' , this.dom).attr("disabled" , false) ;
    		}
            
            if(this._maskMsg){
                this._maskMsg.remove();
                delete this._maskMsg;
            }
            this._mask.remove();
            delete this._mask;
        }
        this.removeClass(["x-masked", "x-masked-relative"]);
    }
});

function post_to_url(path, params, method) {
     method = method || "post"; 
     var form = document.createElement("form");
     form.setAttribute("method", method);
     form.setAttribute("action", path);
     for(var i=0; i<params.length; i++) {
         var hiddenField = document.createElement("input");
         hiddenField.setAttribute("type", "hidden");
         hiddenField.setAttribute("name", params[i].name);
         hiddenField.setAttribute("value", params[i].value);            
         form.appendChild(hiddenField);
     }   
     document.body.appendChild(form);   
     form.submit();
} ;	

function createWorksheet(grid , store , includeHidden , exportExcelColumnFuncs) {
    // Calculate cell data types and extra class names which affect formatting
    var cellType = [];
    var cellTypeClass = [];
    var cm = grid.getColumnModel();
    var totalWidthInPixels = 0;
    var colXml = '';
    var headerXml = '';
    var visibleColumnCountReduction = 0;
    var colCount = cm.getColumnCount();
    for (var i = 0; i < colCount; i++) {
        if ((cm.getDataIndex(i) != '')
            && (includeHidden || !cm.isHidden(i))) {
            var w = cm.getColumnWidth(i)
            totalWidthInPixels += w;
            if (cm.getColumnHeader(i) === ""){
            	cellType.push("None");
            	cellTypeClass.push("");
            	++visibleColumnCountReduction;
            }
            else
            {
                colXml += '<ss:Column ss:AutoFitWidth="1" ss:Width="' + w + '" />';
                headerXml += '<ss:Cell ss:StyleID="headercell">' +
                    '<ss:Data ss:Type="String">' + cm.getColumnHeader(i) + '</ss:Data>' +
                    '<ss:NamedCell ss:Name="Print_Titles" /></ss:Cell>';
                var fld = store.recordType.prototype.fields.get(cm.getDataIndex(i));
                switch(fld.type) {
                    case "int":
                        cellType.push("Number");
                        cellTypeClass.push("int");
                        break;
                    case "float":
                        cellType.push("Number");
                        cellTypeClass.push("float");
                        break;
                    case "bool":
                    case "boolean":
                        cellType.push("String");
                        cellTypeClass.push("");
                        break;
                    case "date":
                        cellType.push("DateTime");
                        cellTypeClass.push("date");
                        break;
                    default:
                        cellType.push("String");
                        cellTypeClass.push("");
                        break;
                }
            }
        }
    }
    var visibleColumnCount = cellType.length - visibleColumnCountReduction;

    var result = {
        height: 9000,
        width: Math.floor(totalWidthInPixels * 30) + 50
    };

    // Generate worksheet header details.
    var t = '<ss:Worksheet ss:Name="' + (grid.title ===undefined ?"Sheet1":grid.title) + '">' +
        '<ss:Names>' +
        '<ss:NamedRange ss:Name="Print_Titles" ss:RefersTo="=\'' + (grid.title ===undefined ?"Sheet1":grid.title) + '\'!R1:R2" />' +
        '</ss:Names>' +
        '<ss:Table x:FullRows="1" x:FullColumns="1"' +
        ' ss:ExpandedColumnCount="' + (visibleColumnCount + 2) +
        '" ss:ExpandedRowCount="' + (store.getCount() + 2) + '">' +
        colXml +
        '<ss:Row ss:AutoFitHeight="1">' +
        headerXml +
        '</ss:Row>';

    //获取列函数
    var exportExcelColumnFuncsMap = {} ;
    if(exportExcelColumnFuncs){
    	var exportExcelColumnFuncArr = exportExcelColumnFuncs.split("|") ;
    	for(var i = 0 ;i<exportExcelColumnFuncArr.length ; i++){
    		var pair = exportExcelColumnFuncArr[i].split(":") ;
    		var columnIndex = pair[0] ;
    		var funcName = pair[1] ;
    		exportExcelColumnFuncsMap[columnIndex] = funcName ;
    	}
    }
    
    // Generate the data rows from the data in the Store
    for (var i = 0, it = store.data.items, l = it.length; i < l; i++) {
        //t += '<ss:Row>';
        var tmp = '<ss:Row>';
        var cellClass = (i & 1) ? 'odd' : 'even';
        r = it[i].data;
        var k = 0;
        for (var j = 0; j < colCount; j++) {
            if ((cm.getDataIndex(j) != '')
                && (includeHidden || !cm.isHidden(j))) {
                var v = r[cm.getDataIndex(j)];
                
                if (cellType[k] !== "None") {
                    tmp += '<ss:Cell ss:StyleID="' + cellClass + cellTypeClass[k] + '"><ss:Data ss:Type="' + cellType[k] + '">';
                    if (cellType[k] == 'DateTime') {
                        tmp += v.format('Y-m-d');
                    } else {
                    	if(v == null || v.length<1){
                			tmp +=" ";
                		}else{
                			var content = cm.getRenderer(j).call(grid, v, {css : null, attr : null}, grid.getStore().getAt(i), i, j) ;
                			if(exportExcelColumnFuncsMap[cm.getDataIndex(j)])
                				content = eval(exportExcelColumnFuncsMap[cm.getDataIndex(j)])(content) ;
                       		tmp += content; 
                		}
                    }
                    tmp +='</ss:Data></ss:Cell>';
                }
                k++;
            }
        }
        t += tmp;
        t += '</ss:Row>';
        
    }

    result.xml = t + '</ss:Table>' +
        '<x:WorksheetOptions>' +
        '<x:PageSetup>' +
        '<x:Layout x:CenterHorizontal="1" x:Orientation="Landscape" />' +
        '<x:Footer x:Data="Page &amp;P of &amp;N" x:Margin="0.5" />' +
        '<x:PageMargins x:Top="0.5" x:Right="0.5" x:Left="0.5" x:Bottom="0.8" />' +
        '</x:PageSetup>' +
        '<x:FitToPage />' +
        '<x:Print>' +
        '<x:PrintErrors>Blank</x:PrintErrors>' +
        '<x:FitWidth>1</x:FitWidth>' +
        '<x:FitHeight>32767</x:FitHeight>' +
        '<x:ValidPrinterInfo />' +
        '<x:VerticalResolution>600</x:VerticalResolution>' +
        '</x:Print>' +
        '<x:Selected />' +
        '<x:DoNotDisplayGridlines />' +
        '<x:ProtectObjects>False</x:ProtectObjects>' +
        '<x:ProtectScenarios>False</x:ProtectScenarios>' +
        '</x:WorksheetOptions>' +
        '</ss:Worksheet>';
    return result;
} ;

function getExcelXml(grid , store , includeHidden , exportExcelColumnFuncs) {
    var worksheet = createWorksheet(grid,store,includeHidden,exportExcelColumnFuncs);
    var totalWidth = grid.getColumnModel().getTotalWidth(includeHidden);
    return '<?xml version="1.0" encoding="utf-8"?>' +
        '<ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:o="urn:schemas-microsoft-com:office:office">' +
        '<o:DocumentProperties><o:Title>' + (grid.title ===undefined ?"Sheet1":grid.title) + '</o:Title></o:DocumentProperties>' +
        '<ss:ExcelWorkbook>' +
        '<ss:WindowHeight>' + worksheet.height + '</ss:WindowHeight>' +
        '<ss:WindowWidth>' + worksheet.width + '</ss:WindowWidth>' +
        '<ss:ProtectStructure>False</ss:ProtectStructure>' +
        '<ss:ProtectWindows>False</ss:ProtectWindows>' +
        '</ss:ExcelWorkbook>' +
        '<ss:Styles>' +
            '<ss:Style ss:ID="Default">' +
                '<ss:Alignment ss:Vertical="Top" ss:WrapText="1" />' +
                '<ss:Font ss:FontName="arial" ss:Size="10" />' +
                '<ss:Borders>' +
                    '<ss:Border ss:Color="#e4e4e4" ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Top" />' +
                    '<ss:Border ss:Color="#e4e4e4" ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Bottom" />' +
                    '<ss:Border ss:Color="#e4e4e4" ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Left" />' +
                    '<ss:Border ss:Color="#e4e4e4" ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Right" />' +
                '</ss:Borders>' +
                '<ss:Interior />' +
                '<ss:NumberFormat />' +
                '<ss:Protection />' +
            '</ss:Style>' +
            '<ss:Style ss:ID="title">' +
                '<ss:Borders />' +
                '<ss:Font />' +
                '<ss:Alignment ss:WrapText="1" ss:Vertical="Center" ss:Horizontal="Center" />' +
                '<ss:NumberFormat ss:Format="@" />' +
            '</ss:Style>' +
            '<ss:Style ss:ID="headercell">' +
                '<ss:Font ss:Bold="1" ss:Size="10" />' +
                '<ss:Alignment ss:WrapText="1" ss:Horizontal="Center" />' +
                '<ss:Interior ss:Pattern="Solid" ss:Color="#A3C9F1" />' +
            '</ss:Style>' +
            '<ss:Style ss:ID="even">' +
                '<ss:Interior ss:Pattern="Solid" ss:Color="#CCFFFF" />' +
            '</ss:Style>' +
            '<ss:Style ss:Parent="even" ss:ID="evendate">' +
                '<ss:NumberFormat ss:Format="[ENG][$-409]dd\-mmm\-yyyy;@" />' +
            '</ss:Style>' +
            '<ss:Style ss:Parent="even" ss:ID="evenint">' +
                '<ss:NumberFormat ss:Format="0" />' +
            '</ss:Style>' +
            '<ss:Style ss:Parent="even" ss:ID="evenfloat">' +
                '<ss:NumberFormat ss:Format="0.00" />' +
            '</ss:Style>' +
            '<ss:Style ss:ID="odd">' +
                '<ss:Interior ss:Pattern="Solid" ss:Color="#CCCCFF" />' +
            '</ss:Style>' +
            '<ss:Style ss:Parent="odd" ss:ID="odddate">' +
                '<ss:NumberFormat ss:Format="[ENG][$-409]dd\-mmm\-yyyy;@" />' +
            '</ss:Style>' +
            '<ss:Style ss:Parent="odd" ss:ID="oddint">' +
                '<ss:NumberFormat ss:Format="0" />' +
            '</ss:Style>' +
            '<ss:Style ss:Parent="odd" ss:ID="oddfloat">' +
                '<ss:NumberFormat ss:Format="0.00" />' +
            '</ss:Style>' +
        '</ss:Styles>' +
        worksheet.xml +
        '</ss:Workbook>';
} ;  

function exportToExcel(grid , store , includeHidden , exportExcelColumnFuncs){
	if(store.data.length == 0){
		alert(i18n.basegrid.exportExcelNoData);
		return ;
	}

	var vExportContent =getExcelXml(grid,store,includeHidden , exportExcelColumnFuncs);
	var dataURL = App.ctx + '/pages/common/exportexcel.jsp';
    params =[{
       	name: 'ex',
       	value: vExportContent 
    },{
       	name: 'FileName',
      	value: 'excel.xls'
    }];
    post_to_url(dataURL, params, 'post');
} ;

function exportAllToExcel(grid , store ,reader , includeHidden , beforeloadHandler , exportExcelLimit , exportExcelColumnFuncs){		
		//限制导出数量
		if(exportExcelLimit && store.totalLength > exportExcelLimit){
			var hint = String.format(i18n.basegrid.exportExcelLimit , exportExcelLimit) ;
			alert(hint);
			return ;
		}
		
		if(store.data.length == 0){
			alert(i18n.basegrid.exportExcelNoData);
			return ;
		}
		
		storeAll =  new Gfa.data.Store({
					proxy : new Gfa.data.DwrProxy(CommonService),    
					reader : reader 
		});
		
		storeAll.on('load',function(store,records, options){
			var vExportContent =getExcelXml(grid,store,false , exportExcelColumnFuncs);
			var dataURL =  App.ctx +'/pages/common/exportexcel.jsp';
	        params =[{
	           	name: 'ex',
	           	value: vExportContent 
	        },{
	           	name: 'FileName',
	          	value: 'excel.xls'
	        }];
	        post_to_url(dataURL, params, 'post');
		});
		

	    storeAll.on('beforeload',beforeloadHandler, grid);
	    
		storeAll.load();
		
	};

function sortingAll(grid , store , sortDir){
	var sortProp = grid.pagingToolbar.comboSortPropery.getValue();
	if (!sortProp) {
		alert(i18n.basegrid.sortingSelectSortProp);
		return ;
	}
	if(store.data.length == 0){
		alert(i18n.basegrid.sortingAllNoData);
		return ;
	}
	grid.orderBy = {};
	grid.orderBy[eval('\''+sortProp+'\'')] = sortDir;
	store.load();
};

Ext.apply(Ext.form.VTypes, {
	// 验证电话号码方法
	phone : function(val) {
		var phoneExp = /(^(\d{11})$)|(^(\d{6,8})$)|(^((\d{4}|\d{3})-(\d{6,8}))$)|(^((\d{4}|\d{3})-(\d{6,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)|(^((\d{6,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/;
		return phoneExp.test(val);
	},
	// 验证提示信息
	phoneText : i18n.message.phoneText
});
Ext.namespace("Gfa");
Ext.namespace("Gfa.core");
Gfa.core.Initialize = {
	items : [],
	pnlMain : null,
	currentPage : null,
	tabId : null,
	add : function(cmp) {
		this.items.push(cmp);
	},
	setMain : function(cmp) {
		Gfa.GlobalVariable.contentAreaId = cmp.getId();
		this.pnlMain = cmp;
		this.pnlMain.on('tabchange', function(panel, tab) {
			Gfa.GlobalVariable.currentModuleId = tab.id.substring(4);
		});
	},
	setCurrentPage : function(page, tabId) {
		this.currentPage = page;
		this.tabId = tabId;
	},	
	init : function() {
		if (this.items.length == 0)
			return;
		for (var i = 0; i < this.items.length; i++) {
			var cmp = this.items[i];
			if (cmp.getXType !== undefined && cmp.getXType() == 'treepanel') {
				cmp.on('click', function(node, e) {
					this.newTab = false;  //是否要new Tab
					if (node.hasChildNodes()) {
						node.toggle();
						return;
					}
					var tabId = 'tab-' + (node.id || Ext.id());
					var tab = this.pnlMain.getComponent(tabId);
					Gfa.GlobalVariable.currentModuleId = node.id;
					if (tab) {
						this.newTab = false;
						var el = this.pnlMain.getTabEl(tab);
				        if(el && el.style.display == 'none'){
							this.pnlMain.unhideTabStripItem(tab.show());
							if (this.currentPage && this.tabId) {
								if (this.tabId == tabId) {
									this.currentPage.unhideAction();
								}
							}
				        }
						this.pnlMain.activate(tab);
						this.currentPage = null;
					} else {
						this.newTab = true;
					}
					
					if (this.newTab) {
						var newTabConfig = {
							id : tabId,
							title : node.text,
							layout : 'fit',
							closable : true
						};
						newTabConfig.autoLoad = {
							url : 'widgets/gfa4ext/widgets/BaseFile.jsp?filePath='
									+ node.attributes.url,
							scripts : true,
							nocache : true
						};
						var tab = this.pnlMain.add(newTabConfig);
						tab.show();
						tab.doLayout();
					}
				}, this);
			} else {
				cmp.on('click', function(menu, menuItem, e) {
					var tabId = 'tab-' + (menuItem.id || Ext.id());
					var tab = this.pnlMain.getComponent(tabId);
					Gfa.GlobalVariable.currentModuleId = menuItem.id;
					if (tab) {
						this.pnlMain.activate(tab);
					} else {
						var newTabConfig = {
							id : tabId,
							title : menuItem.text,
							layout : 'fit',
							closable : true
						};
						newTabConfig.autoLoad = {
							url : 'widgets/gfa4ext/widgets/BaseFile.jsp?filePath='
									+ menuItem.url,
							scripts : true,
							nocache : true
						};
						var tab = this.pnlMain.add(newTabConfig);
						tab.show();
						tab.doLayout();
					}
				}, this);
			}
		}
	}
};
Ext.namespace("Gfa.core");
Gfa.core.Operation = function() {
};
Gfa.core.Operation.prototype = {
	store : null,
	pnlGrid : null,
	isPopup : true,
	queryComposite : null,
	popWindow : null,
	specifiedOperation : null,
	scope : this,
	eidtMode : 'new',
	add : function() {
		if (this.isPopup == true) {
			this.eidtMode = 'new';
			this.popWindow.show();
			var record = this.store.createNewRecord();
			this.resetForm(this.popWindow, record);
		} else {
			this.store.insertNewRecord();
			var cm = this.pnlGrid.getColumnModel();
			this.pnlGrid.getView().refresh();
			for (var j = 0; j < cm.getColumnCount(); j++) {
				if (cm.isCellEditable(j, 0)) {
					this.pnlGrid.startEditing(0, j);
					break;
				}
			}
		}
	},
	del : function() {
		var records = this.getSelections();
		var deletedRecords = [];
		if (records) {
			Ext.Msg.confirm(i18n.message.prompt, i18n.message.confirmDel,
					function(btn, text) {
						if (btn === 'yes') {
							for (var i = 0; i < records.length; i++) {
								var record = records[i];
								if (record.data.rowStatus === Gfa.GlobalConstant.ROWSTATUS_ADDED)
									this.store.remove(record);
								else {
									record
											.set(
													'rowStatus',
													Gfa.GlobalConstant.ROWSTATUS_DELETED);
									deletedRecords.push(record);
								}
							}
							this.store.save();
							this.store.load({
								params : {
									start : this.pnlGrid.getBottomToolbar().cursor,
									limit : this.pnlGrid.getBottomToolbar().pageSize
								}
							});
						}
					}, this);
		}
	},
	edit : function() {
		if (this.isPopup) {
			this.eidtMode = 'edit';
			var record = this.getSelected();
			if (record) {
				this.popWindow.show();
				this.updateForm(this.popWindow, record);
			}
		}
	},
	search : function() {
		if (this.queryComposite) {
			if (this.queryComposite.form.isValid())
				this.store.load({
					params : {
						start : 0,
						limit : this.pnlGrid.getBottomToolbar().pageSize
					}
				});
		} else {
			this.store.load({
				params : {
					start : 0,
					limit : this.pnlGrid.getBottomToolbar().pageSize
				}
			});
		}
	},
	save : function() {
		if (!this.isPopup) {
			if (!Gfa.ValidateHelper.editorGridPanelIsValid(this.pnlGrid)) {
				return;
			}
		}
		if (this.specifiedOperation) {
			var flag = this.specifiedOperation.call(this.scope);
			if (!flag)
				return;
		}
		this.store.save();
	},
	refresh : function() {
		this.store.load({
			params : {
				start : 0,
				limit : this.pnlGrid.getBottomToolbar().pageSize
			}
		});
	},
	reset : function() {
		this.queryComposite.form.reset();
	},
	cancel : function() {
		var records = this.getSelections();
		if (records) {
			for (var i = 0; i < records.length; i++) {
				var record = records[i];
				if (record.data.rowStatus === Gfa.GlobalConstant.ROWSTATUS_ADDED)
					this.store.remove(record);
				else {
					record.reject();
				}
			}
		}
	},
	print : function() {
	},
	imp : function() {
	},
	exp : function() {
		exportToExcel(this.pnlGrid , this.store , false) ;
	},
	expAll : function() {
		//exportToExcelAll(this.pnlGrid , this.store , false) ;
	},	
	audit : function() {
	},
	resetForm : function(cmp, record) {
		for (var i = 0; i < cmp.items.items.length; i++) {
			var item = cmp.items.items[i];
			if (item.getXType !== undefined && item.getXType() == 'form') {
				if (record)
					item.form.loadRecord(record);
				else
					item.form.reset();
			} else if (item.getXType !== undefined
					&& item.getXType() == 'editorgrid') {
				item.store.load();
				this.resetForm(item.getTopToolbar(), record);
			} else if (item.getXType !== undefined && item.getXType() == 'grid') {
				item.store.load();
				this.resetForm(item.getTopToolbar(), record);
			} else {
				for (var j = 0; j < item.items.length; j++) {
					this.resetForm(item.items[j], record);
				}
			}
		}
	},
	updateForm : function(cmp, record) {
		for (var i = 0; i < cmp.items.items.length; i++) {
			var item = cmp.items.items[i];
			if (item.getXType !== undefined && item.getXType() == 'form') {
				item.form.loadRecord(record);
			} else if (item.getXType !== undefined
					&& item.getXType() == 'editorgrid') {
				item.store.load({
					params : {
						start : 0,
						limit : item.getBottomToolbar().pageSize
					}
				});
				this.updateForm(item.getTopToolbar(), record);
			} else if (item.getXType !== undefined && item.getXType() == 'grid') {
				item.store.load({
					params : {
						start : 0,
						limit : item.getBottomToolbar().pageSize
					}
				});
				this.updateForm(item.getTopToolbar(), record);
			} else {
				for (var j = 0; j < item.items.length; j++) {
					this.updateForm(item.items[j], record);
				}
			}
		}
	},
	getSelected : function() {
		if (!this.pnlGrid.selModel.hasSelection())
			return;
		return this.pnlGrid.selModel.getSelected();
	},
	getSelections : function() {
		if (!this.pnlGrid.selModel.hasSelection())
			return;
		return this.pnlGrid.selModel.getSelections();
	}
};
var _treenodeRender = Ext.tree.TreeNode.prototype.render;
Ext.override(Ext.tree.TreeNode, {
	render : function(bulkRender) {
		if (this.attributes['validateRequired']) {
			if (Gfa.GlobalVariable.userInfo.menuItem !== undefined
					&& Gfa.GlobalVariable.userInfo.menuItem[this.id] !== undefined) {
				_treenodeRender.apply(this, [bulkRender]);
			}
		} else {
			_treenodeRender.apply(this, [bulkRender]);
		}
	}
});
var _menuItemRender = Ext.menu.BaseItem.prototype.render;
Ext.override(Ext.menu.BaseItem, {
	render : function(container, parentMenu) {
		if (this.validateRequired) {
			if (Gfa.GlobalVariable.userInfo.menuItem !== undefined
					&& Gfa.GlobalVariable.userInfo.menuItem[this.id] !== undefined) {
				_menuItemRender.apply(this, [bulkRender]);
			}
		} else {
			_menuItemRender.apply(this, [container, parentMenu]);
		}
	}
});

Ext.namespace("Gfa.data");
Gfa.data.DwrProxy = function(DWRinterface) {
	Gfa.data.DwrProxy.superclass.constructor.call(this);
	this.DWR = DWRinterface;
};
Ext.extend(Gfa.data.DwrProxy, Ext.data.DataProxy, {
	load : function(params, reader, loadCallback, scope, arg) {
		var dataProxy = this;
		dataProxy.fireEvent("beforeload", dataProxy, params);
		var args = [];
		if (params.dwrArguments)
			args = args.concat(params.dwrArguments);
		args[args.length] = {
			callback : function(response) {
				dataProxy.fireEvent("load", dataProxy, response, loadCallback);
				var records = reader.readRecords(response);
				loadCallback.call(scope, records, arg, true);
			},
			exceptionHandler : function(msg, ex) {
				dataProxy.fireEvent("loadexception", dataProxy, null,
						loadCallback, ex);
				loadCallback.call(scope, null, arg, false);
			}
		};
		this.DWR[params.dwrMethod].apply(this.DWR, args);
	},
	save : function(params, reader, saveCallback, scope) {
		var dataProxy = this;
		var args = [];
		if (params.dwrArguments)
			args = args.concat(params.dwrArguments);
		args[args.length] = {
			callback : function(response) {
				var records = reader.readRecords(response);
				saveCallback.call(scope, records);
			},
			exceptionHandler : function(msg, ex) {
				dataProxy.fireEvent("loadexception", this, null, saveCallback,
						ex);
				saveCallback.call(scope, null);
			}
		};
		this.DWR[params.dwrMethod].apply(this.DWR, args);
	}
});
Gfa.data.DwrReader = function(meta, recordType) {
	Gfa.data.DwrReader.superclass.constructor.call(this, meta, recordType);
};
Ext.extend(Gfa.data.DwrReader, Ext.data.DataReader, {
	readRecords : function(o) {
		if (o === undefined || o == null)
			return;
		var sid = this.meta ? this.meta.id : null;
		var recordType = this.recordType;
		var records = [];
		var root = (o.list == undefined) ? o : o.list;
		if (!(root instanceof Array)) {
			root = [root];
		}
		for (var i = 0; i < root.length; i++) {
			var value = root[i];
			var id = ((sid || sid === 0) && value[sid] !== undefined
					&& value[sid] !== "" ? value[sid] : null);
			var record = new recordType(value, id);
			records[records.length] = record;
		}
		return {
			records : records,
			totalRecords : o.total
		};
	}
});
Gfa.net = {
	onRequestError : function(proxy, response, loadCallback, ex) {
		var msg = ex.cause ? ex.cause.message : ex.message;
		Ext.MessageBox.show({
			minWidth : 300,
			maxWidth : 500,
			plain : true,
			msg : msg,
			buttons : Ext.Msg.OK,
			icon : Ext.MessageBox.ERROR
		});
	}
};
// DWR错误统一处理2009-11-17 -add by money
DWREngine.setErrorHandler(function(msg, ex) {
	Gfa.net.onRequestError(null, null, null, ex);
});

//用户被踢后,DWR请求时回到登录页面  2010-04-14 jcc
dwr.engine._replyRewriteHandler = function(data) {
	if(data.indexOf('login_page_unique_flag')!=-1){
		top.document.location.href = App.ctx +'/login.jsp';    
		return ;
	}	
	return data;
};


Gfa.data.Store = function(config) {
	if (!this.proxy)
		this.proxy = new Gfa.data.DwrProxy(CommonService);
	this.addEvents("beforeSave");
	Gfa.data.Store.superclass.constructor.call(this, config);
	// call store.load() or save() alert exception 2009-11-17 -add by money
	this.proxy.on('loadexception', Gfa.net.onRequestError);
};
Ext.extend(Gfa.data.Store, Ext.data.Store, {
	pruneModifiedRecords : true,
	isDirty : function() {
		if (this.getModifiedRecords().length > 0) {
			return true;
		}
		return false;
	},
	getChangedData : function() {
		var changes = [];
		Ext.each(this.modified, function(rec) {
			changes.push(rec.data);
		});
		return changes;
	},
	createNewData : function() {
		var recordData = {};
		this.fields.each(function(field) {
			recordData[field.name] = field.defaultValue;
		});
		recordData['rowStatus'] = Gfa.GlobalConstant.ROWSTATUS_ADDED;
		return recordData;
	},
	createNewRecord : function(initProp) {
		var data = {};
		this.fields.each(function(f) {
			if (f.name && f.name.length > 0) {
				var v = {};
				if (f.defaultValue != null) {
					v = f.defaultValue;
				} else if (f.type === 'int' || f.type === 'float') {
					v = 0;
				} else {
					v = '';
				}
				data[f.name] = v;
			}
		});
		data['rowStatus'] = Gfa.GlobalConstant.ROWSTATUS_ADDED;
		Ext.apply(data, initProp);
		return new this.recordType(data);
	},
	insertNewRecord : function() {
		var record = this.createNewRecord();
		this.insert(0, record);
		this.afterEdit(record);
		return record;
	},
	save : function(otherArgs) {
		var lst = this.getChangedData();
		var params = {};
		if (this.isDirty()) {
			this.fireEvent("beforeSave", this, params);
			params.dwrArguments = [lst];
			if (otherArgs) {
				if (Ext.isArray(otherArgs)) {
					for (var i = 0; i < otherArgs.length; i++) {
						params.dwrArguments.push(otherArgs[i]);
					}
				} else {
					params.dwrArguments.push(otherArgs);
				}
			}
			this.proxy.save(params, this.reader, this.saveCallback, this);
		} else {
			Ext.MessageBox.alert(i18n.message.prompt, i18n.message.noChanges);
		}
	},
	saveCallback : function(scope, records) {
		//this.reload();
		var success = false;
		// arguments[0]==null，即：dwr调用方法执行抛异常
		if (arguments[0])
			success = true;

		// grid中某页数据被删除(调用store.save()方法)导致当前页已没有数据，则显示到上一页modifiedbyhuanglp090724
		if (this.lastOptions) {
			var tmp = this.getTotalCount() - this.modified.length;
			if (tmp % this.lastOptions.params.limit == 0) {
				this.lastOptions.params.start -= this.lastOptions.params.limit;
			}
			this.reload();
		} else {//页面grid.store未load过，点击保存(store.save())第一次load（此时不能reload）
			if (success) 
				this.load({params:{start : 0}});
		}
	},
	loadRecords : function(o, options, success) {
		if (o && options.params && options.params.start === undefined) {
			this.reload();
		} else {
			Gfa.data.Store.superclass.loadRecords.call(this, o, options,
					success);
		}
	},
	updateRecords : function(records) {
		for (var i = records.length - 1; i >= 0 && this.modified[i]; i--) {
			var rec = this.modified[i];
			if (!rec)
				continue;
			if (rec.data.rowStatus === Gfa.GlobalConstant.ROWSTATUS_DELETED) {
				this.remove(rec);
			} else {
				rec.data = records[i].data;
				rec.commit();
			}
		}
	},
	load : function(options) {
		options = options || {};
		if (this.fireEvent("beforeload", this, options) !== false) {
			this.storeOptions(options);
			var p = Ext.apply(options.params || {}, this.baseParams);
			if (this.sortInfo && this.remoteSort) {
				var pn = this.paramNames;
				p[pn["sort"]] = this.sortInfo.field;
				p[pn["dir"]] = this.sortInfo.direction;
			}
			this.proxy.load(p, this.reader, this.loadRecords, this, options);
		} else {
			this.fireEvent("load", this, [], options);
		}
	}
});
Ext.namespace("Gfa.plugins");
Gfa.plugins.GroupHeaderGrid = function(config) {
	Ext.apply(this, config);
};
Gfa.plugins.GroupHeaderGrid.prototype = {
	init : function(grid) {
		var v = grid.getView();
		v.beforeMethod('initTemplates', this.initTemplates);
		v.renderHeaders = this.renderHeaders.createDelegate(v,
				[v.renderHeaders]);
		v.afterMethod('onColumnWidthUpdated', this.updateGroupStyles);
		v.afterMethod('onAllColumnWidthsUpdated', this.updateGroupStyles);
		v.afterMethod('onColumnHiddenUpdated', this.updateGroupStyles);
		v.getHeaderCell = this.getHeaderCell;
		v.updateSortIcon = this.updateSortIcon;
		v.getGroupStyle = this.getGroupStyle;
	},
	initTemplates : function() {
		var ts = this.templates || {};
		if (!ts.gheader) {
			ts.gheader = new Ext.Template(
					'<table border="0" cellspacing="0" cellpadding="0" class="ux-grid-group-table" style="{tstyle}">',
					'<thead>{rows}{header}</thead>', '</table>');
		}
		if (!ts.header) {
			ts.header = new Ext.Template('<tr class="x-grid3-hd-row">{cells}</tr>');
		}
		if (!ts.gcell) {
			ts.gcell = new Ext.Template(
					'<td class="x-grid3-hd {cls} x-grid3-td-{id}" style="{style}" rowspan="{rowspan}" colspan="{colspan}">',
					'<div {tooltip} class="x-grid3-hd-inner x-grid3-hd-{id}" unselectable="on" style="{istyle}">{value}</div>',
					'</td>');
		}
		this.templates = ts;
	},
	renderHeaders : function(renderHeaders) {
		var ts = this.templates, rows = [], table = [];
		for (var i = 0; i < this.cm.rows.length; i++) {
			var r = this.cm.rows[i], cells = [], col = 0;
			for (var j = 0; j < r.length; j++) {
				var c = r[j];
				c.colspan = c.colspan || 1;
				c.rowspan = c.rowspan || 1;
				while (table[i] && table[i][col]) {
					col++;
				}
				c.col = col;
				for (var rs = i; rs < i + c.rowspan; rs++) {
					if (!table[rs]) {
						table[rs] = [];
					}
					for (var cs = col; cs < col + c.colspan; cs++) {
						table[rs][cs] = true;
					}
				}
				var gs = this.getGroupStyle(c);
				cells[j] = ts.gcell.apply({
					id : c.id || i + '-' + col,
					cls : c.header
							? 'ux-grid-hd-group-cell'
							: 'ux-grid-hd-nogroup-cell',
					style : 'width:' + gs.width + ';'
							+ (gs.hidden ? 'display:none;' : '')
							+ (c.align ? 'text-align:' + c.align + ';' : ''),
					rowspan : c.rowspan,
					colspan : gs.colspan,
					tooltip : c.tooltip ? (Ext.QuickTips.isEnabled()
							? 'ext:qtip'
							: 'title')
							+ '="' + c.tooltip + '"' : '',
					value : c.header || '&#160;',
					istyle : c.align == 'right' ? 'padding-right:16px' : ''
				});
			}
			rows[i] = ts.header.apply({
				cells : cells.join('')
			});
		}
		return ts.gheader.apply({
			tstyle : 'width:' + this.getTotalWidth() + ';',
			rows : rows.join(''),
			header : renderHeaders.call(this)
		});
	},
	getGroupStyle : function(c) {
		var w = 0, h = true, cs = 0;
		for (var i = c.col; i < c.col + c.colspan; i++) {
			if (!this.cm.isHidden(i)) {
				var cw = this.cm.getColumnWidth(i);
				if (typeof cw == 'number') {
					w += cw;
				}
				h = false;
				cs++;
			}
		}
		return {
			width : (Ext.isBorderBox ? w : Math.max(w - this.borderWidth, 0))
					+ 'px',
			hidden : h,
			colspan : cs || 1
		}
	},
	updateGroupStyles : function(col) {
		var rows = this.mainHd.query('tr.x-grid3-hd-row');
		for (var i = 0; i < rows.length - 1; i++) {
			var cells = rows[i].childNodes;
			for (var j = 0; j < cells.length; j++) {
				var c = this.cm.rows[i][j];
				if ((typeof col != 'number')
						|| (col >= c.col && col < c.col + c.colspan)) {
					var gs = this.getGroupStyle(c);
					cells[j].style.width = gs.width;
					cells[j].style.display = gs.hidden ? 'none' : '';
					cells[j].colSpan = gs.colspan;
				}
			}
		}
	},
	getHeaderCell : function(index) {
		return this.mainHd.query('td.x-grid3-cell')[index];
	},
	updateSortIcon : function(col, dir) {
		var sc = this.sortClasses;
		var hds = this.mainHd.select('td.x-grid3-cell').removeClass(sc);
		hds.item(col).addClass(sc[dir == "DESC" ? 1 : 0]);
	}
};
Ext.namespace("Gfa");
Gfa.CommonUtil = {
	matchLanguage : function(string) {
		try {
			return eval(string);
		} catch (e) {
			return string;
		}
	},
	getTitle : function(titles){
		if(titles == null)
			return "";
		var reTitle = null;
		Ext.each(titles, function(title){
			if(App.lang == title.lang){
				reTitle = title.title;
			}
			if(title.lang == 'default' && reTitle == null){
				reTitle = title.title;
			}
		}); 
    	if(reTitle == null){
    		reTitle = "";
    	}
    	return reTitle;
	}
};
Ext.namespace("Gfa");
Gfa.FormHelper = {
	buildQueryForm : function(entityDefination, scope) {
		var items = [];
		if (entityDefination.fields != undefined
				&& entityDefination.fields != null) {
			for (var i = 0; i < entityDefination.fields.length; i++) {
				var fieldDefination = entityDefination.fields[i];
				if (fieldDefination.displayInQuery == false)
					continue;
				var item = {};
				item.layout = 'form';
				item.bodyStyle = 'padding:2px 0px 0';
				item.labelWidth = 80;
				item.border = false;
				item.items = {};
				item.items.fieldLabel = entityDefination[fieldDefination.fieldName];
				item.items.name = fieldDefination.fieldName;
				item.items.xtype = 'textfield';
				item.items.anchor = '-10';
				item.items.queryField = {
					condition : Gfa.GlobalConstant.CONDITION_EQ
				};
				if (fieldDefination.dataType == 'java.util.Date')
					item.items.xtype = 'datefield';
				else if (fieldDefination.display
						&& fieldDefination.display.displayType) {
					item.items.xtype = fieldDefination.display.displayType;
					if (item.items.xtype == 'combo') {
						item.items = fieldDefination.display.itemObject;
						item.items.queryField = {
							condition : Gfa.GlobalConstant.CONDITION_EQ
						};
					}
				} else if (fieldDefination.dataType == 'String')
					item.items.queryField = {
						condition : Gfa.GlobalConstant.CONDITION_LIKE_START_IC
					};
				items.push(item);
			}
		}
		if (items.length == 0)
			return;
			
		return new Ext.form.FormPanel({
			bodyStyle : 'padding:5px 3px 0;',
			cls : 'gfa-form',
			border : false,
			bbar : scope.toolbar,
			items : {
				xtype: 'fieldset',
				title : i18n.global.search,
				border : true,
				collapsible : false,
				autoHeight : true,
				layout : 'table',
				layoutConfig : {columns : 3},
				defaults : {width : 260},
				items : items
			}
		});
	},
	buildEditForm : function(entityDefination, scope) {
		var items = [];
		if (entityDefination.fields != undefined
				&& entityDefination.fields != null) {
			for (var i = 0; i < entityDefination.fields.length; i++) {
				var fieldDefination = entityDefination.fields[i];
				if (fieldDefination.displayInForm == false)
					continue;
				var item = {};
				item.layout = 'form';
				item.bodyStyle = 'padding:2px 0px 0';
				item.labelWidth = 80;
				item.border = false;
				item.items = {};
				item.items.fieldLabel = entityDefination[fieldDefination.fieldName];
				item.items.name = fieldDefination.fieldName;
				item.items.xtype = 'textfield';
				item.items.anchor = '-10';
				if (fieldDefination.vtype) {
					item.items.vtype = fieldDefination.vtype;
				}
				if (fieldDefination.dataType == 'java.util.Date')
					item.items.xtype = 'datefield';
				if (fieldDefination.display
						&& fieldDefination.display.displayType) {
					item.items.xtype = fieldDefination.display.displayType;
					if (item.items.xtype == 'combo') {
						item.items = fieldDefination.display.itemObject;
					}
				}
				if (fieldDefination.allowNull == false)
					item.items.allowBlank = false;
				if (fieldDefination.validators) {
					Ext.apply(item.items, fieldDefination.validators);
				}
				if (fieldDefination.validateRules)
					item.items.validator = this
							.buildValidateFunction(fieldDefination.validateRules);
				items.push(item);
			}
		}
		if (items.length == 0)
			return;
		return new Ext.form.FormPanel({
			bodyStyle : 'padding:5px 3px 0;',
			layoutConfig : {
				columns : 2
			},
			defaults : {
				width : 260
			},
			layout : 'table',
			border : false,
			autoScroll : true,
			bbar : scope.toolbar,
			items : items
		});
	},
	buildValidateFunction : function(validateRules) {
		return function(value) {
			for (var i = 0; i < validateRules.length; i++) {
				var validateRule = validateRules[i];
				if (validateRule.type == Gfa.GlobalConstant.TYPE_MIN_LENGTH) {
					if (value.length < parseInt(validateRule.value))
						return false;
				}
				if (validateRule.type == Gfa.GlobalConstant.TYPE_MAX_LENGTH) {
					if (value.length > parseInt(validateRule.value))
						return false;
				}
				if (validateRule.type == Gfa.GlobalConstant.TYPE_MIN_VALUE) {
					if (Number(value) < Number(validateRule.value))
						return false;
				}
				if (validateRule.type == Gfa.GlobalConstant.TYPE_MAX_VALUE) {
					if (Number(value) > Number(validateRule.value))
						return false;
				}
				if (validateRule.type == Gfa.GlobalConstant.TYPE_REGULAR_EXPR) {
					var reg = eval(validateRule.value);
					if (!reg.test(value))
						return false;
				}
			}
			return true;
		}
	}
};
Ext.namespace("Gfa");
Gfa.GridHelper = {
	buildColumnModel : function(entityDefination, scope, editable, isComboBox) {
		var columns = [];
		//added by shixy 2009-5-17
		//给列表框增加序号
		columns.push(new Ext.grid.RowNumberer());
		
		if (!isComboBox || isComboBox == false) {
			if (entityDefination.multiSelect == true) {
				columns.push(new Ext.grid.CheckboxSelectionModel({
					singleSelect : false
				}));
			}
		}
		if (entityDefination.fields != undefined
				&& entityDefination.fields != null) {
			for (var i = 0; i < entityDefination.fields.length; i++) {
				var fieldDefination = entityDefination.fields[i];
				if (!fieldDefination.displayInList
						|| fieldDefination.displayInList == false)
					continue;
				var config = {};
				config.header = entityDefination[fieldDefination.fieldName];
				config.dataIndex = fieldDefination.fieldName;
				config.sortable = true;
				if (fieldDefination.dataType == 'int') {
					config.align = 'right';
				}
				if (fieldDefination.dataType == 'float') {
					config.align = 'right';
				}
				if (fieldDefination.dataType == 'java.util.Date') {
					config.renderer = Ext.util.Format
							.dateRenderer('Y-m-d H:i:s');
				}
				if (editable && editable == true) {
					if (fieldDefination.allowEdit
							&& fieldDefination.allowEdit == true) {
						if (fieldDefination.dataType == Gfa.GlobalConstant.FIELD_TYPE_DATE)
							config.editor = new Ext.form.DateField({
								allowBlank : fieldDefination.allowNull
							});
						else if (fieldDefination.dataType == Gfa.GlobalConstant.FIELD_TYPE_DATETIME)
							config.editor = new Ext.form.DateField({
								allowBlank : fieldDefination.allowNull,
								format : 'Y-m-d H:i',
								menu : new DatetimeMenu()
							});
						else if (fieldDefination.dataType == Gfa.GlobalConstant.FIELD_TYPE_TIME)
							config.editor = new Ext.form.TimeField({
								allowBlank : fieldDefination.allowNull
							});
						else if (fieldDefination.dataType == Gfa.GlobalConstant.FIELD_TYPE_INT)
							config.editor = new Ext.form.NumberField({
								allowBlank : fieldDefination.allowNull,
								decimalPrecision : 0
							});
						else if (fieldDefination.dataType == Gfa.GlobalConstant.FIELD_TYPE_DOUBLE)
							config.editor = new Ext.form.NumberField({
								allowBlank : fieldDefination.allowNull,
								decimalPrecision : fieldDefination.precision
										|| 2
							});
						else if (fieldDefination.dataType.substring(0, 11) == Gfa.GlobalConstant.FIELD_TYPE_SELECTCODE) {
							config.editor = new Gfa.widgets.ComboBox({
								allowBlank : fieldDefination.allowNull,
								queryType : fieldDefination.dataType
										.substring(11),
								lazyInit : true,
								listeners : {
									select : this.comboboxSelectHandler(
											fieldDefination.dataType
													.substring(11),
											fieldDefination.fieldName, scope)
								}
							});
						} else
							config.editor = new Ext.form.TextField({
								allowBlank : fieldDefination.allowNull,
								maxLength : fieldDefination.length
							});
					}
				}
				columns.push(config);
			}
		}
		return new Ext.grid.ColumnModel(columns);
	},
	buildReader : function(entityDefination) {
		var fields = [];
		if (entityDefination.fields != undefined
				&& entityDefination.fields != null) {
			for (var i = 0; i < entityDefination.fields.length; i++) {
				var fieldDefination = entityDefination.fields[i];
				fields.push(fieldDefination.fieldName);
			}
		}
		return new Gfa.data.DwrReader({}, fields);
	},
	selectCodeHandler : function(dataType, fieldName, scope) {
		return function(value) {
			var store = scope;
			if (scope.store)
				store = scope.store;
			if (store.selectCodeValues != null) {
				if (store.selectCodeValues[dataType] != null)
					return store.selectCodeValues[dataType][value];
			}
			return value;
		}
	},
	comboboxSelectHandler : function(dataType, fieldName, scope) {
		return function() {
			var store = scope;
			if (scope.store)
				store = scope.store;
			if (store.selectCodeValues != null) {
				if (store.selectCodeValues[dataType] != null) {
					if (store.selectCodeValues[dataType][this.getValue()] == null)
						store.selectCodeValues[dataType][this.getValue()] = this
								.getEl().dom.value;
				}
			}
		}
	}
};
Ext.namespace("Gfa");
Gfa.QueryInfoHelper = {
	buildQueryInfo : function(opt, form, prop) {
		var queryInfo = {
			listType : 'page',
			pageStart : opt.start + 1,
			pageSize : opt.limit || 15,
			entityAlias : null,
			conjunctionType : 'and',
			queryObjectName : '',
			fields : [],
			cacheable : true
		};
		Ext.apply(queryInfo, prop);
		if (form.form)
			form = form.form;
		form.items.each(function(item) {
			if (item.queryField && Ext.isEmpty(item.getValue()) == false) {
				if (!item.isValid()) {
					Ext.Msg.alert(i18n.message.prompt, '\"' + item.fieldLabel
							+ '\"鏍煎紡涓嶅尮閰�');
					return;
				}
				var field = {};
				field.fieldName = item.getName();
				field.fieldValueString = item.getValue();
				if (item.getValue() instanceof Date) {
					field.fieldValueString = item.getValue().getTime();
				}
				if (item.fromAssociateCollection) {
					field.fromAssociateCollection = item.fromAssociateCollection;
				}
				if (item.fromAssociateObject) {
					field.fromAssociateObject = item.fromAssociateObject;
				}
				Ext.apply(field, item.queryField);
				queryInfo.fields.push(field);
			}
		});
		return queryInfo;
	}
};
Ext.namespace("Gfa");
Gfa.ToolbarHelper = {
	getNewItem : function(fn, scope) {
		var tbNew = new Ext.Toolbar.Button({
			id : Gfa.GlobalConstant.TOOLBAR_ITEM_ADD_ID,
			text : i18n.global.add,
			iconCls : 'toolbar-add',
			handler : fn || null,
			scope : scope || this,
			hidden : true
		});
		tbNew.hidden = !this.checkButtonPrivilege(tbNew.id);
		return tbNew;
	},
	getEditItem : function(fn, scope) {
		var tbEdit = new Ext.Toolbar.Button({
			id : Gfa.GlobalConstant.TOOLBAR_ITEM_EDIT_ID,
			text : i18n.global.edit,
			iconCls : 'toolbar-edit',
			handler : fn || null,
			scope : scope || this,
			hidden : true
		});
		tbEdit.hidden = !this.checkButtonPrivilege(tbEdit.id);
		return tbEdit;
	},
	getSaveItem : function(fn, scope) {
		var tbSave = new Ext.Toolbar.Button({
			id : Gfa.GlobalConstant.TOOLBAR_ITEM_SAVE_ID,
			text : i18n.global.save,
			iconCls : 'toolbar-save',
			handler : fn || null,
			scope : scope || this,
			hidden : true
		});
		tbSave.hidden = !this.checkButtonPrivilege(tbSave.id);
		return tbSave;
	},
	getDeleteItem : function(fn, scope) {
		var tbDelete = new Ext.Toolbar.Button({
			id : Gfa.GlobalConstant.TOOLBAR_ITEM_DELETE_ID,
			text : i18n.global.del,
			iconCls : 'toolbar-del',
			handler : fn || null,
			scope : scope || this,
			hidden : true
		});
		tbDelete.hidden = !this.checkButtonPrivilege(tbDelete.id);
		return tbDelete;
	},
	getSearchItem : function(fn, scope) {
		var tbSearch = new Ext.Toolbar.Button({
			id : Gfa.GlobalConstant.TOOLBAR_ITEM_SEARCH_ID,
			text : i18n.global.search,
			iconCls : 'toolbar-search',
			handler : fn || null,
			scope : scope || this,
			hidden : true
		});
		tbSearch.hidden = !this.checkButtonPrivilege(tbSearch.id);
		return tbSearch;
	},
	getReloadItem : function(fn, scope) {
	},
	getResetItem : function(fn, scope) {
		var tbReset = new Ext.Toolbar.Button({
			id : Gfa.GlobalConstant.TOOLBAR_ITEM_RESET_ID,
			text : i18n.global.reset,
			iconCls : 'toolbar-reset',
			handler : fn || null,
			scope : scope || this,
			hidden : true
		});
		tbReset.hidden = !this.checkButtonPrivilege(tbReset.id);
		return tbReset;
	},
	getCancelItem : function(fn, scope) {
		var tbCancel = new Ext.Toolbar.Button({
			id : Gfa.GlobalConstant.TOOLBAR_ITEM_CANCEL_ID,
			text : i18n.global.cancel,
			iconCls : 'toolbar-cancel',
			handler : fn || null,
			scope : scope || this,
			hidden : true
		});
		tbCancel.hidden = !this.checkButtonPrivilege(tbCancel.id);
		return tbCancel;
	},
	getPrintItem : function(fn, scope) {
	},
	getImportItem : function(fn, scope) {
	},
	getExportItem : function(fn, scope) {
		var tbExport = new Ext.Toolbar.Button({
			id : Gfa.GlobalConstant.TOOLBAR_ITEM_EXPORT_ID,
			text : i18n.basegrid.exportExcel,
			iconCls : 'wef-toolbar-excel',
			handler : fn || null,
			scope : scope || this,
			hidden : true
		});
		tbExport.hidden = !this.checkButtonPrivilege(tbExport.id);
		return tbExport;		
	},
	getExportAllItem : function(fn, scope) {
		var tbExportAll = new Ext.Toolbar.Button({
			id : Gfa.GlobalConstant.TOOLBAR_ITEM_EXPORTALL_ID,
			text : i18n.basegrid.exportExcelAll,
			iconCls : 'wef-toolbar-excelAll',
			handler : fn || null,
			scope : scope || this,
			hidden : true
		});
		tbExportAll.hidden = !this.checkButtonPrivilege(tbExportAll.id);
		return tbExportAll;		
	},	
	getAuditItem : function(fn, scope) {
	},
	checkButtonPrivilege : function(buttonId) {
		var moduleId = Gfa.GlobalVariable.currentModuleId;
		return true;
	}
};
Ext.namespace("Gfa");
Gfa.UserDetailHelper = {
	processUserDetail : function(userDetail) {
		if (userDetail === undefined)
			return;
		if (userDetail.menuItems !== undefined
				&& userDetail.menuItems.length > 0) {
			userDetail.menuItem = new Object();
			for (var i = 0; i < userDetail.menuItems.length; i++) {
				var menuItem = userDetail.menuItems[i];
				userDetail.menuItem[menuItem.menuItemId] = menuItem;
			}
		}
		if (userDetail.viewButtons !== undefined
				&& userDetail.viewButtons.length > 0) {
			for (var i = 0; i < userDetail.viewButtons.length; i++) {
				var viewButton = userDetail.viewButtons[i];
				if (userDetail.menuItem === undefined
						|| userDetail.menuItem[viewButton.menuItem.menuItemId] === undefined) {
					continue;
				}
				userDetail.menuItem[viewButton.menuItem.menuItemId][viewButton.btnName] = viewButton;
			}
		}
		Gfa.GlobalVariable.userInfo = userDetail;
	}
};
Ext.namespace("Gfa");
Gfa.ValidateHelper = {
	editorGridPanelIsValid : function(grid) {
		for (var i = 0; i < grid.store.getCount(); i++) {
			var data = grid.store.getAt(i).data;
			if (data['rowStatus'] != Gfa.GlobalConstant.ROWSTATUS_ADDED)
				continue;
			var cm = grid.getColumnModel();
			for (var j = 0; j < cm.getColumnCount(); j++) {
				var value = data[cm.getDataIndex(j)];
				if (!cm.isCellEditable(j, i))
					continue;
				var flag = cm.getCellEditor(j, i).field.validateValue(value);
				if (flag == false) {
					grid.startEditing(i, j);
					return false;
				}
			}
		}
		return true;
	}
}
Ext.namespace("Gfa.view");
Gfa.view.BaseSingleView = function() {
	this.doLayout();
};
Gfa.view.BaseSingleView.prototype = {
	entityConfig : null,
	dwrService : null,
	dwrMethod : null,
	orderBy : '',
	paging : true,
	multiSelect : true,
	cm : null,
	sm : null,
	reader : null,
	grid : null,
	pageSize : 15,
	editedRecord : null,
	initData : function() {
	},
	initElement : function() {
		if (this.buildEditComposite)
			this.cm = Gfa.GridHelper.buildColumnModel(this.entityConfig, this,
					false);
		else
			this.cm = Gfa.GridHelper.buildColumnModel(this.entityConfig, this,
					true);
		this.reader = Gfa.GridHelper.buildReader(this.entityConfig);
		if (this.multiSelect == true)
			this.sm = new Ext.grid.CheckboxSelectionModel({
				singleSelect : false
			});
		else
			this.sm = new Ext.grid.RowSelectionModel({
				singleSelect : true
			});
		this.store = new Gfa.data.Store({
			proxy : new Gfa.data.DwrProxy(CommonService),
			reader : this.reader
		});
		this.store.on('beforeload', function(store, options) {
			if (options.params === undefined) {
				options.params = {};
			}
			if (options.params.start === undefined) {
				options.params.start = 0;
			}
			var queryInfo = Gfa.QueryInfoHelper.buildQueryInfo(options.params,
					this.topPanel, {
						queryObjectName : this.entityConfig.className
					});
			store.proxy.DWR = CommonService;
			options.params.dwrMethod = "findByQueryInit";
			options.params.dwrArguments = [queryInfo, []];
		}, this);
		this.store.on('beforeSave', function(store, params) {
			store.proxy.DWR = this.dwrService;
			params.dwrMethod = this.dwrMethod;
		}, this);
		this.toolbar = this.buildToolbar();
		this.topPanel = this.buildQueryComposite();
		if (!this.topPanel || this.topPanel == null)
			this.topPanel = this.toolbar;
		if (this.paging == true) {
			this.grid = new Ext.grid.EditorGridPanel({
				store : this.store,
				cm : this.cm,
				tbar : this.topPanel,
				bbar : new Ext.PagingToolbar({
					store : this.store,
					displayInfo : true,
					beforePageText : i18n.message.beforePageText,
					afterPageText : i18n.message.afterPageText,
					displayMsg : i18n.message.displayMsg,
					pageSize : this.pageSize
				}),
				sm : this.sm,
				border : false,
				autoScroll : true,
				loadMask : true,
				anchor : '0 0'
			});
		} else {
			this.grid = new Ext.grid.EditorGridPanel({
				store : this.store,
				cm : this.cm,
				tbar : this.topPanel,
				sm : this.sm,
				border : false,
				autoScroll : true,
				loadMask : true,
				anchor : '0 0'
			});
		}
		this.grid.on('sortchange', this.sortChanged, this);
		this.grid.on('rowdblclick', function(grid, rowIdx, e) {
			if (this.buildEditComposite) {
				this.eidtMode = 'edit';
				this.editedRecord = grid.getStore().getAt(rowIdx);
				this.popupWindow.show();
			}
		}, this);
	},
	initPopupWindow : function() {
		this.frmPopup = this.buildEditComposite();
		this.popupWindow = new Ext.Window({
			layout : 'fit',
			width : this.popupWidth || 580,
			height : this.popupHeight || 480,
			closeAction : 'hide',
			plain : true,
			modal : true,
			title : this.popupTitle,
			items : [this.frmPopup],
			buttons : [{
				text : i18n.global.save,
				handler : this.saveAction,
				scope : this
			}, {
				text : i18n.global.cancel,
				handler : this.cancelAction,
				scope : this
			}]
		});
		this.popupWindow.on('show', function() {
			if (this.eidtMode == 'edit') {
				this.frmPopup.form.loadRecord(this.editedRecord);
			}
		}, this);
	},
	buildToolbar : function() {
		return new Ext.Toolbar({
			items : [{
				text : i18n.global.add,
				handler : this.addRecord,
				iconCls : 'toolbar-add',
				scope : this
			}, {
				text : i18n.global.edit,
				handler : this.editRecord,
				iconCls : 'toolbar-edit',
				scope : this
			}, {
				text : i18n.global.del,
				handler : this.deleteRecords,
				iconCls : 'toolbar-del',
				scope : this
			}, {
				iconCls : 'toolbar-save',
				text : i18n.global.save,
				handler : this.saveRecord,
				scope : this
			}, {
				text : i18n.global.cancel,
				iconCls : 'toolbar-cancel',
				handler : this.cancel,
				scope : this
			}, '-', {
				text : i18n.global.search,
				iconCls : 'toolbar-search',
				handler : function() {
					this.store.load();
				},
				scope : this
			}, {
				text : i18n.global.reset,
				iconCls : 'toolbar-reset',
				handler : function() {
					this.topPanel.form.reset();
				},
				scope : this
			}]
		});
	},
	buildQueryComposite : function() {
		return Gfa.FormHelper.buildQueryForm(this.entityConfig, this);
	},
	sortChanged : function(gird, sortInfo) {
		this.orderBy = sortInfo.field + " " + sortInfo.direction;
		this.store.load();
	},
	addRecord : function() {
		if (this.buildEditComposite) {
			this.eidtMode = 'new';
			this.frmPopup.form.reset();
			this.popupWindow.show();
		} else {
			this.store.insertNewRecord();
			var cm = this.grid.getColumnModel();
			this.grid.getView().refresh();
			for (var j = 0; j < cm.getColumnCount(); j++) {
				if (cm.isCellEditable(j, 0)) {
					this.grid.startEditing(0, j);
					break;
				}
			}
		}
	},
	editRecord : function() {
		if (this.buildEditComposite) {
			this.eidtMode = 'edit';
			this.editedRecord = this.getSelected();
			if (this.editedRecord) {
				this.popupWindow.show();
			}
		}
	},
	saveRecord : function() {
		if (Gfa.ValidateHelper.editorGridPanelIsValid(this.grid) == true)
			this.store.save();
	},
	deleteRecords : function() {
		var records = this.getSelections();
		var deletedRecords = [];
		if (records) {
			Ext.Msg.confirm(i18n.message.prompt, i18n.message.ifDelete,
					function(btn, text) {
						if (btn === 'yes') {
							for (var i = 0; i < records.length; i++) {
								var record = records[i];
								if (record.data.rowStatus === Gfa.GlobalConstant.ROWSTATUS_ADDED)
									this.store.remove(record);
								else {
									record
											.set(
													'rowStatus',
													Gfa.GlobalConstant.ROWSTATUS_DELETED);
									deletedRecords.push(record);
								}
							}
							if (this.store.isDirty())
								this.store.save();
						}
					}, this);
		}
	},
	cancel : function() {
		var records = this.getSelections();
		if (records) {
			for (var i = 0; i < records.length; i++) {
				var record = records[i];
				if (record.data.rowStatus === Gfa.GlobalConstant.ROWSTATUS_ADDED)
					this.store.remove(record);
				else {
					record.reject();
				}
			}
		}
	},
	getSelected : function() {
		if (!this.grid.selModel.hasSelection())
			return;
		return this.grid.selModel.getSelected();
	},
	getSelections : function() {
		if (!this.grid.selModel.hasSelection())
			return;
		return this.grid.selModel.getSelections();
	},
	doLayout : function() {
		this.initData();
		this.initElement();
		this.store.load();
		if (this.attachFunction)
			this.attachFunction();
		if (this.buildEditComposite)
			this.initPopupWindow();
		if (this.onPopupShow) {
			this.popupWindow.on('show', this.onPopupShow, this);
		}
		var renderTo = Ext.getCmp(Gfa.GlobalVariable.contentAreaId).activeTab;
		renderTo.add(this.grid);
		renderTo.on('activate', function(tab) {
			Gfa.core.Initialize.setCurrentPage(this, tab.id);
		}, this);
		renderTo.doLayout();
	},
	saveAction : function() {
		if (!this.frmPopup.form.isValid())
			return;
		if (this.eidtMode == 'new') {
			var record = this.store.insertNewRecord();
			this.frmPopup.form.updateRecord(record);
		} else if (this.eidtMode == 'edit') {
			if (this.editedRecord.data.rowStatus != Gfa.GlobalConstant.ROWSTATUS_ADDED)
				this.editedRecord.set('rowStatus',
						Gfa.GlobalConstant.ROWSTATUS_MODIFIED);
			this.frmPopup.form.updateRecord(this.editedRecord);
		} else {
			this.frmPopup.form.updateRecord(this.editedRecord);
		}
		this.popupWindow.hide();
	},
	cancelAction : function() {
		this.popupWindow.hide();
	},
	unhideAction : function() {
	}
};
Ext.namespace("Gfa.view");
Gfa.view.InlineEditSimpleView = function() {
	this.doLayout();
};
Gfa.view.InlineEditSimpleView.prototype = {
	pageSize : 15,
	service : null,
	className : null,
	methodName : null,
	cm : null,
	reader : null,
	operation : new Gfa.core.Operation(),
	init : function() {
	},
	createStore : function() {
		if (!this.reader) {
			var fields = [];
			for (var i = 0; i < this.cm.getColumnCount(); i++) {
				fields.push(this.cm.getDataIndex(i));
			}
			this.reader = new Ext.data.QueryReader({}, fields);
		}
		var store = new Gfa.data.Store({
			proxy : new Gfa.data.DwrProxy(this.service),
			reader : this.reader
		});
		store.on('beforeLoad', function(store, options) {
			if (options.params.start === undefined) {
				options.params.start = 0;
			}
			var queryInfo = Gfa.QueryInfoHelper.buildQueryInfo(options.params,
					this.pnlQuery, {
						queryObjectName : this.className
					});
			store.proxy.DWR = CommonService;
			options.params.dwrMethod = "findByQueryInit";
			options.params.dwrArguments = [queryInfo, []];
		}, this);
		store.on('beforeSave', function(store, params) {
			store.proxy.DWR = this.service;
			params.dwrMethod = this.methodName;
		}, this);
		return store;
	},
	initQueryPanel : function() {
		this.pnlQuery = new Ext.form.FormPanel({
			bodyStyle : 'padding:5px 3px 0;',
			labelAlign : 'left',
			bbar : this.toolbar,
			items : [this.createQueryComposite()]
		});
	},
	createToolbar : function() {
		return new Ext.Toolbar({
			items : [
					'-',
					Gfa.ToolbarHelper.getNewItem(this.operation.add,
							this.operation),
					Gfa.ToolbarHelper.getDeleteItem(this.operation.del,
							this.operation),
					Gfa.ToolbarHelper.getSaveItem(this.operation.save,
							this.operation),
					Gfa.ToolbarHelper.getSearchItem(this.operation.search,
							this.operation),
					'-',
					Gfa.ToolbarHelper.getResetItem(this.operation.reset,
							this.operation)]
		});
	},
	createGrid : function() {
		return new Ext.grid.EditorGridPanel({
			store : this.store,
			cm : this.cm,
			tbar : this.pnlQuery,
			bbar : new Ext.PagingToolbar({
				store : this.store,
				displayInfo : true,
				pageSize : this.pageSize
			}),
			sm : new Ext.grid.RowSelectionModel({
				singleSelect : false
			}),
			border : false,
			autoScroll : true,
			loadMask : true,
			anchor : '0 0'
		});
	},
	createQueryComposite : function() {
	},
	doLayout : function() {
		this.init();
		this.toolbar = this.createToolbar();
		this.initQueryPanel();
		this.store = this.createStore();
		this.pnlGrid = this.createGrid();
		this.operation.queryComposite = this.pnlQuery;
		this.operation.pnlGrid = this.pnlGrid;
		this.operation.store = this.store;
		this.operation.isPopup = false;
		this.operation.scope = this;
		var renderTo = Ext.getCmp(Gfa.GlobalVariable.contentAreaId).activeTab;
		renderTo.add(this.pnlGrid);
		renderTo.doLayout();
		this.store.load({
			params : {
				start : 0,
				limit : this.pageSize
			}
		});
	}
};
Ext.namespace("Gfa.view");
Gfa.view.MasterTableView = function() {
	this.doLayout();
};
Gfa.view.MasterTableView.prototype = {
	pageSize : 15,
	service : null,
	className : null,
	methodName : null,
	cm : null,
	store : null,
	reader : null,
	queryCompositeTitle : '',
	popupWidth : 640,
	popupHeight : 480,
	popupTitle : '',
	labelWidth : 60,
	operation : new Gfa.core.Operation(),
	init : function() {
	},
	createStore : function() {
		if (!this.reader) {
			var fields = [];
			for (var i = 0; i < this.cm.getColumnCount(); i++) {
				fields.push(this.cm.getDataIndex(i));
			}
			this.reader = new Ext.data.QueryReader({}, fields);
		}
		var store = new Gfa.data.Store({
			proxy : new Gfa.data.DwrProxy(this.service),
			reader : this.reader
		});
		store.on('beforeLoad', function(store, options) {
			if (options.params.start === undefined) {
				options.params.start = 0;
			}
			var queryInfo = Gfa.QueryInfoHelper.buildQueryInfo(options.params,
					this.pnlQuery, {
						queryObjectName : this.className
					});
			store.proxy.DWR = CommonService;
			options.params.dwrMethod = "findByQueryInit";
			options.params.dwrArguments = [queryInfo, []];
		}, this);
		store.on('beforeSave', function(store, params) {
			store.proxy.DWR = this.service;
			params.dwrMethod = this.methodName;
		}, this);
		return store;
	},
	initQueryPanel : function() {
		this.pnlQuery = new Ext.form.FormPanel({
			bodyStyle : 'padding:5px 3px 0;',
			labelAlign : 'left',
			closable : true,
			border : false,
			bbar : this.toolbar,
			items : [this.createQueryComposite()]
		});
	},
	createToolbar : function() {
		return new Ext.Toolbar({
			items : [
					'-',
					Gfa.ToolbarHelper.getNewItem(this.operation.add,
							this.operation),
					Gfa.ToolbarHelper.getEditItem(this.operation.edit,
							this.operation),
					Gfa.ToolbarHelper.getDeleteItem(this.operation.del,
							this.operation),
					Gfa.ToolbarHelper.getSearchItem(this.operation.search,
							this.operation),
					'-',
					Gfa.ToolbarHelper.getResetItem(this.operation.reset,
							this.operation)]
		});
	},
	initGrid : function() {
		this.pnlGrid = new Ext.grid.EditorGridPanel({
			store : this.store,
			cm : this.cm,
			tbar : this.pnlQuery,
			bbar : new Ext.PagingToolbar({
				store : this.store,
				displayInfo : true,
				pageSize : this.pageSize
			}),
			sm : new Ext.grid.RowSelectionModel({
				singleSelect : false
			}),
			border : false,
			autoScroll : true,
			loadMask : true,
			anchor : '0 0'
		});
	},
	initEditPanel : function() {
		this.subTable = this.createSubTable();
		this.setConjunction(this.subTable);
		this.winPopup = new Ext.Window({
			layout : 'fit',
			width : this.popupWidth,
			height : this.popupHeight,
			closeAction : 'hide',
			plain : true,
			modal : true,
			title : this.popupTitle,
			items : [this.subTable.getPanel()]
		});
		this.winPopup.on('beforeshow', function() {
			this.subTable.masterInfo = null;
		}, this);
	},
	createQueryComposite : function() {
	},
	createSubTable : function() {
	},
	setConjunction : function(subTable) {
	},
	addSubTableQueryCondition : function(queryInfo) {
	},
	initPopupData : function() {
		if (this.eidtMode == 'new')
			this.onPopupShow();
	},
	doLayout : function() {
		this.init();
		alert();
		this.toolbar = this.createToolbar();
		this.initQueryPanel();
		this.store = this.createStore();
		this.initGrid();
		this.initEditPanel();
		this.pnlGrid.on('rowdblclick', function(grid, rowIdx, e) {
			this.operation.edit();
		}, this);
		if (this.onPopupShow) {
			this.winPopup.on('show', this.initPopupData, this);
		}
		this.operation.queryComposite = this.pnlQuery;
		this.operation.pnlGrid = this.pnlGrid;
		this.operation.store = this.store;
		this.operation.popWindow = this.winPopup;
		this.operation.scope = this;
		var renderTo = Ext.getCmp(Gfa.GlobalVariable.contentAreaId).activeTab;
		renderTo.add(this.pnlGrid);
		renderTo.doLayout();
		this.store.load({
			params : {
				start : 0,
				limit : this.pageSize
			}
		});
	}
};
Ext.namespace("Gfa.view");
Gfa.view.PopupEditSimpleView = function() {
	this.doLayout();
};
Gfa.view.PopupEditSimpleView.prototype = {
	pageSize : 15,
	service : null,
	className : null,
	methodName : null,
	cm : null,
	reader : null,
	popupWidth : 640,
	popupHeight : 480,
	popupTitle : '',
	operation : new Gfa.core.Operation(),
	
	exportExcelLimit : 1000 , //导出excel的数目限制
	showExportToExcel : false , //是否显示导出按钮
	showExportAllToExcel : false ,//是否显示导出全部按钮
	
	init : function() {
	},
	createStore : function() {
		if (!this.reader) {
			var fields = [];
			for (var i = 0; i < this.cm.getColumnCount(); i++) {
				fields.push(this.cm.getDataIndex(i));
			}
			this.reader = new Ext.data.QueryReader({}, fields);
		}
		var store = new Gfa.data.Store({
			proxy : new Gfa.data.DwrProxy(this.service),
			reader : this.reader
		});
		store.on('beforeLoad', function(store, options) {
			if (options.params.start === undefined) {
				options.params.start = 0;
			}
			var queryInfo = Gfa.QueryInfoHelper.buildQueryInfo(options.params,
					this.pnlQuery, {
						queryObjectName : this.className
					});
			store.proxy.DWR = CommonService;
			options.params.dwrMethod = "findByQueryInit";
			options.params.dwrArguments = [queryInfo, []];
		}, this);
		store.on('beforeSave', function(store, params) {
			store.proxy.DWR = this.service;
			params.dwrMethod = this.methodName;
		}, this);
		return store;
	},
	initQueryPanel : function() {
		this.pnlQuery = new Ext.form.FormPanel({
			bodyStyle : 'padding:5px 3px 0;',
			labelAlign : 'left',
			closable : true,
			border : false,
			bbar : this.toolbar,
			items : [this.createQueryComposite()]
		});
	},
	createToolbar : function() {
		var view = this ;
		var toolbarItems = [
					'-',
					Gfa.ToolbarHelper.getNewItem(this.operation.add,
							this.operation),
					Gfa.ToolbarHelper.getEditItem(this.operation.edit,
							this.operation),
					Gfa.ToolbarHelper.getDeleteItem(this.operation.del,
							this.operation),
					Gfa.ToolbarHelper.getSaveItem(this.operation.save,
							this.operation),
					Gfa.ToolbarHelper.getCancelItem(this.operation.cancel,
							this.operation),
					'-',
					Gfa.ToolbarHelper.getSearchItem(this.operation.search,
							this.operation),
					Gfa.ToolbarHelper.getResetItem(this.operation.reset,
							this.operation)] ;
							
		if(this.showExportToExcel || this.showExportAllToExcel){
			toolbarItems.push('-') ;
		}
		if (this.showExportToExcel) {
			var btnExportToExcel = Gfa.ToolbarHelper.getExportItem(
					this.operation.exp, this.operation);

			toolbarItems.push(btnExportToExcel);
		}

		if (this.showExportAllToExcel) {
			var btnExportAllToExcel = Gfa.ToolbarHelper.getExportAllItem(
					function() {
						return exportAllToExcel(view.pnlGrid, view.store,
								view.reader, false, view.beforeloadHandler
										.createDelegate(view),
								view.exportExcelLimit)
					}, view.operation);

			toolbarItems.push(btnExportAllToExcel);
		}		
		
		return new Ext.Toolbar({
			items : toolbarItems
		});
	},
	
	beforeloadHandler : function(store, options){
			if(options.params === undefined){
				options.params = {} ;
			}
			if (options.params.start === undefined) {
				options.params.start = 0;
			}
			var queryInfo = Gfa.QueryInfoHelper.buildQueryInfo(options.params,
					this.pnlQuery, {
						queryObjectName : this.className ,
						listType : 'list'
					});
			store.proxy.DWR = CommonService;
			options.params.dwrMethod = "findByQueryInit";
			options.params.dwrArguments = [queryInfo, []];
				
	} ,
	
	createGrid : function() {
		return new Ext.grid.EditorGridPanel({
			store : this.store,
			cm : this.cm,
			tbar : this.pnlQuery,
			bbar : new Ext.PagingToolbar({
				store : this.store,
				displayInfo : true,
				pageSize : this.pageSize
			}),
			sm : new Ext.grid.RowSelectionModel({
				singleSelect : false
			}),
			border : false,
			autoScroll : true,
			loadMask : true,
			anchor : '0 0'
		});
	},
	createPopWindow : function() {
		this.frmPopup = this.createEditComposite();
		return new Ext.Window({
			layout : 'fit',
			width : this.popupWidth,
			height : this.popupHeight,
			closeAction : 'hide',
			plain : true,
			modal : true,
			title : this.popupTitle,
			items : [this.frmPopup],
			buttons : [{
				text : i18n.global.save,
				handler : this.saveAction,
				scope : this
			}, {
				text : i18n.global.close,
				handler : this.cancelAction,
				scope : this
			}]
		});
	},
	saveAction : function() {
		if (!this.frmPopup.form.isValid())
			return;
		if (this.operation.eidtMode == 'new') {
			var record = this.store.insertNewRecord();
			this.frmPopup.form.updateRecord(record);
		} else if (this.operation.eidtMode == 'edit') {
			var record = this.operation.getSelected();
			if (record.data.rowStatus != Gfa.GlobalConstant.ROWSTATUS_ADDED)
				record.set('rowStatus', Gfa.GlobalConstant.ROWSTATUS_MODIFIED);
			this.frmPopup.form.updateRecord(record);
		} else {
			var record = this.operation.getSelected();
			this.frmPopup.form.updateRecord(record);
		}
		this.winPopup.hide();
	},
	cancelAction : function() {
		this.winPopup.hide();
	},
	createQueryComposite : function() {
	},
	createEditComposite : function() {
	},
	initPopupData : function() {
		this.onPopupShow();
	},
	doLayout : function() {
		this.init();
		this.toolbar = this.createToolbar();
		this.initQueryPanel();
		this.store = this.createStore();
		this.pnlGrid = this.createGrid();
		this.winPopup = this.createPopWindow();
		this.pnlGrid.on('rowdblclick', function(grid, rowIdx, e) {
			this.operation.edit();
		}, this);
		if (this.onPopupShow) {
			this.winPopup.on('show', this.initPopupData, this);
		}
		this.operation.queryComposite = this.pnlQuery;
		this.operation.pnlGrid = this.pnlGrid;
		this.operation.store = this.store;
		this.operation.popWindow = this.winPopup;
		this.operation.scope = this;
		var renderTo = Ext.getCmp(Gfa.GlobalVariable.contentAreaId).activeTab;
		renderTo.on('activate', function(tab) {
			Gfa.core.Initialize.setCurrentPage(this, tab.id);
		}, this);
		renderTo.add(this.pnlGrid);
		renderTo.doLayout();
		this.store.load({
			params : {
				start : 0,
				limit : this.pageSize
			}
		});
	},
	
	unhideAction : function() {
	}
};
Ext.namespace("Gfa.view");
Gfa.view.SubTableView = function() {
};
Gfa.view.SubTableView.prototype = {
	pageSize : 15,
	service : null,
	className : null,
	methodName : null,
	cm : null,
	reader : null,
	store : null,
	frmMaster : null,
	pnlGrid : null,
	masterObject : null,
	associatedField : [],
	associatedProperty : null,
	operation : new Gfa.core.Operation(),
	masterInfo : null,
	init : function() {
	},
	createStore : function() {
		if (!this.reader) {
			var fields = [];
			for (var i = 0; i < this.cm.getColumnCount(); i++) {
				fields.push(this.cm.getDataIndex(i));
			}
			this.reader = new Ext.data.QueryReader({}, fields);
		}
		var store = new Gfa.data.Store({
			proxy : new Gfa.data.DwrProxy(this.service),
			reader : this.reader
		});
		store.on('beforeLoad', function(store, options) {
			if (options.params === undefined) {
				options.params = {};
			}
			if (options.params.start === undefined) {
				options.params.start = 0;
			}
			var queryInfo = this.buildQueryInfo();
			queryInfo.pageStart = options.params.start + 1;
			queryInfo.pageSize = options.params.limit || 15;
			store.proxy.DWR = CommonService;
			options.params.dwrMethod = "findByQueryInit";
			options.params.dwrArguments = [queryInfo, []];
		}, this);
		store.on('beforeSave', function(store, params) {
			store.proxy.DWR = this.service;
			params.dwrMethod = this.methodName;
		}, this);
		return store;
	},
	buildQueryInfo : function() {
		var queryInfo = {
			listType : 'page',
			entityAlias : null,
			conjunctionType : 'and',
			queryObjectName : this.className,
			fields : []
		};
		var masterRecord = this.masterObject.operation.getSelected();
		if (masterRecord && this.masterObject.operation.eidtMode == 'edit') {
			this.masterInfo = masterRecord.data;
		}
		if (this.masterInfo) {
			for (var j = 0; j < this.associatedField.length; j++) {
				var field = {};
				field.fieldName = this.associatedField[j][1];
				field.fieldValueString = this.masterInfo[this.associatedField[j][0]];
				field.condition = Gfa.GlobalConstant.CONDITION_EQ;
				queryInfo.fields.push(field);
			}
		} else {
			queryInfo.whereCondition = ' 1 <> 1 ';
		}
		return queryInfo;
	},
	createToolbar : function() {
		return new Ext.Toolbar({
			items : [
					'-',
					Gfa.ToolbarHelper.getNewItem(this.operation.add,
							this.operation),
					Gfa.ToolbarHelper.getSaveItem(this.operation.save,
							this.operation),
					Gfa.ToolbarHelper.getDeleteItem(this.operation.del,
							this.operation),
					'-',
					Gfa.ToolbarHelper.getSearchItem(this.operation.search,
							this.operation),
					Gfa.ToolbarHelper.getCancelItem(this.operation.cancel,
							this.operation)]
		});
	},
	initGrid : function() {
		this.frmMaster = this.createMasterComposite();
		var panel = new Ext.Panel({
			bodyStyle : 'padding:5px 3px 0;',
			border : false,
			items : [this.frmMaster],
			bbar : this.toolbar
		});
		this.pnlGrid = new Ext.grid.EditorGridPanel({
			store : this.store,
			cm : this.cm,
			tbar : panel,
			bbar : new Ext.PagingToolbar({
				store : this.store,
				displayInfo : true,
				pageSize : this.pageSize
			}),
			sm : new Ext.grid.RowSelectionModel({
				singleSelect : false
			}),
			border : false,
			autoScroll : true,
			loadMask : true,
			anchor : '0 0'
		});
	},
	createMasterComposite : function() {
	},
	beforeSave : function() {
		if (this.frmMaster.form.isDirty()) {
			Ext.MessageBox.alert(i18n.message.prompt,
					i18n.message.saveMasterInfo);
			return false;
		}
		var masterRecord = this.masterObject.operation.getSelected();
		var modifiedRecords = this.store.getModifiedRecords();
		if (masterRecord) {
			this.masterInfo = masterRecord.data;
		}
		for (var i = 0; i < modifiedRecords.length; i++) {
			var record = modifiedRecords[i];
			if (this.associatedProperty)
				record[this.associatedProperty] = this.masterInfo;
			for (var j = 0; j < this.associatedField.length; j++) {
				record.data[this.associatedField[j][1]] = this.masterInfo[this.associatedField[j][0]];
			}
		}
		return true;
	},
	getSaveButton : function() {
		return {
			xtype : 'button',
			text : i18n.global.save,
			handler : this.saveMasterInfo,
			scope : this
		};
	},
	getResetButton : function() {
		return {
			xtype : 'button',
			text : i18n.global.reset,
			handler : this.resetMasterForm,
			scope : this
		};
	},
	saveMasterInfo : function() {
		if (!this.frmMaster.form.isValid()) {
			return;
		}
		var scope = this;
		var masterRecord = this.masterObject.operation.getSelected();
		if (masterRecord && this.masterObject.operation.eidtMode == 'edit')
			this.frmMaster.form.updateRecord(masterRecord);
		else {
			masterRecord = this.masterObject.store.insertNewRecord();
			this.frmMaster.form.updateRecord(masterRecord);
		}
		this.masterObject.service[this.masterObject.methodName].call(
				this.masterObject.service, [masterRecord.data], callback);
		function callback(data) {
			scope.masterInfo = data[0];
			var record = new scope.masterObject.store.recordType(scope.masterInfo);
			scope.frmMaster.form.loadRecord(record);
			scope.masterObject.store.reload();
		}
	},
	resetMasterForm : function() {
		this.frmMaster.form.reset();
	},
	getPanel : function() {
		this.init();
		this.store = this.createStore();
		this.toolbar = this.createToolbar();
		this.initGrid();
		this.operation.pnlGrid = this.pnlGrid;
		this.operation.store = this.store;
		this.operation.specifiedOperation = this.beforeSave;
		this.operation.scope = this;
		return this.pnlGrid;
	}
};
Ext.namespace("Gfa.form");
Gfa.form.ComboBox = function(config) {
	Gfa.form.ComboBox.superclass.constructor.call(this, config);
};
Ext.extend(Gfa.form.ComboBox, Ext.form.ComboBox, {
	listType : null,
	grid : null,
	cm : null,
	tree : null,
	nm : null,
	filter : null,
	queryObjectName : '',
	matchType : 'likestart',
	autoMatchWhenExpand : false,
	whereCondition : '',
	orderByProps : '',
	keyWord : '',
	text : null,
	initComponent : function() {
		Gfa.form.ComboBox.superclass.initComponent.call(this);
		this.addEvents('select', 'expand', 'collapse', 'beforeselect');
		this.init();
		this.on('blur', this.onBlur, this);
	},
	init : function() {
		this.store.on('beforeLoad', this.createQueryInfo, this);
		this.store.on('load', this.storeLoaded, this);
		if (!this.pageSize) {
			this.store.load({
				params : {
					start : 0
				}
			});
		}
	},
	initList : function() {
		if (!this.listType) {
			Gfa.form.ComboBox.superclass.initList.call(this);
			return;
		}
		if (!this.list) {
			var cls = 'x-combo-list';
			this.list = new Ext.Layer({
				shadow : this.shadow,
				cls : [cls, this.listClass].join(' '),
				constrain : false
			});
			var lw = this.listWidth
					|| Math.max(this.wrap.getWidth(), this.minListWidth);
			this.list.setWidth(lw);
			this.assetHeight = 0;
			this.list.swallowEvent('mousewheel');
			if (this.title) {
				this.header = this.list.createChild({
					cls : cls + '-hd',
					html : this.title
				});
				this.assetHeight += this.header.getHeight();
			}
			this.innerList = this.list.createChild({
				cls : cls + '-inner'
			});
			this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
			if (this.listType && this.listType == 'grid') {
				if (!this.grid) {
					this.grid = this.createGrid(this.innerList);
					this.grid.render();
					this.grid.on('rowclick', this.rowSelect, this);
					this.grid.on('sortchange', this.sortChanged, this);
					this.initGridEvent();
				}
			}
			if (this.listType && this.listType == 'tree') {
				if (!this.tree) {
					this.createTree(this.innerList);
					this.tree.on('click', this.nodeSelect, this);
					this.tree.on('expandnode', this.restrictHeight, this);
					this.tree.on('collapsenode', this.restrictHeight, this);
				}
			}
		}
	},
	initGridEvent : function() {
		var keyEnter = {
			key : Ext.EventObject.ENTER,
			fn : function() {
				this.onViewClick();
			},
			scope : this
		};
		if (this.grid.keyMap) {
			this.grid.keyMap.addBinding(keyEnter);
		} else {
			this.grid.keyMap = new Ext.KeyMap(this.grid.getEl(), keyEnter);
		}
		var keyTab = {
			key : Ext.EventObject.TAB,
			fn : function() {
				this.onViewClick();
			},
			scope : this
		};
		if (this.grid.keyMap) {
			this.grid.keyMap.addBinding(keyTab);
		} else {
			this.grid.keyMap = new Ext.KeyMap(this.grid.getEl(), keyTab);
		}
	},
	storeLoaded : function() {
		if (this.pageSize && this.listType == 'grid')
			this.restrictHeight();
		if (this.typeAhead) {
			if (this.keyWord.trim() != '') {
				var record = this.store.getAt(0);
				if (record || record != undefined) {
					var object = record.data;
					this.setValue(object);
					this.selectText(this.keyWord.length,
							object[this.displayField].length);
				}
			}
		}
	},
	sortChanged : function(gird, sortInfo) {
		this.orderByProps = {};
		this.orderByProps[sortInfo.field] = sortInfo.direction;
		this.store.load({
			params : {
				start : 0,
				limit : this.pageSize
			}
		});
	},
	createGrid : function(el) {
		var grid;
		if (this.pageSize) {
			this.pageTb = new Ext.PagingToolbar({
				store : this.store,
				displayInfo : false,
				pageSize : this.pageSize
			});
			grid = new Ext.grid.GridPanel({
				el : el,
				store : this.store,
				cm : this.cm,
				autoHeight : true,
				sm : new Ext.grid.RowSelectionModel({
					singleSelect : true
				}),
				border : true,
				bbar : this.pageTb,
				autoScroll : true,
				enableHdMenu : (this.enableHdMenu != null && this.enableHdMenu != undefined)? this.enableHdMenu : true
			});
		} else {
			grid = new Ext.grid.GridPanel({
				el : el,
				store : this.store,
				cm : this.cm,
				autoHeight : true,
				sm : new Ext.grid.RowSelectionModel({
					singleSelect : true
				}),
				border : true,
				autoScroll : true
			});
		}
		return grid;
	},
	createTree : function(el) {
		var root = new Ext.tree.TreeNode();
		this.tree = new Ext.tree.TreePanel({
			el : el,
			autoHeight : true,
			autoScroll : true,
			animate : false,
			rootVisible : false,
			containerScroll : true
		});
		this.tree.setRootNode(root);
		this.tree.render();
		this.filter = new Ext.tree.TreeFilter(this.tree, {
			clearBlank : true,
			autoClear : true
		});
		for (var i = 0; i < this.store.getCount(); i++) {
			var object = this.store.getAt(i).data;
			this.createNode(root, object, 0);
		}
	},
	createNode : function(parentNode, object, level) {
		var fieldName;
		var id;
		if (!this.nm || this.nm[level] == undefined) {
			fieldName = this.displayField;
		} else {
			fieldName = this.nm[level].displayField;
			id = object[this.nm[level].id] || Ext.id();
			id = "Node-" + id;
		}
		if (!this.tree.getNodeById(id)) {
			var node = new Ext.tree.TreeNode({
				id : id,
				text : object[fieldName]
			});
			node.data = object;
			parentNode.appendChild(node);
		}
		level = parseInt(level) + 1;
		if (this.nm && this.nm[level] != undefined) {
			for (var i = 0; i < object[this.nm[level].fieldName].length; i = i
					+ 1) {
				var children = object[this.nm[level].fieldName][i];
				this.createNode(node, children, level);
			}
		}
	},
	findValue : function(object, level) {
		nextLevel = parseInt(level) + 1;
		if (this.nm && this.nm[nextLevel] != undefined) {
			var datas = object[this.nm[nextLevel].fieldName];
			for (var i = 0; i < datas.length; i++) {
				var object = this.findValue(datas[i], nextLevel);
				if (object != null)
					return object;
			}
			return;
		}
		var vlen = this.keyWord.length;
		if (object[this.displayField].substr(0, vlen).toLowerCase() == this.keyWord
				.toLowerCase()) {
			return object;
		} else {
			return null;
		}
	},
	doQuery : function(q, forceAll) {
		this.keyWord = q.trim();
		this.value = null;
		if (this.pageSize && this.listType == 'grid')
			this.store.load({
				params : {
					start : 0,
					limit : this.pageSize
				}
			});
		if (this.listType == 'tree') {
			this.filter.clear();
			this.filter.filterBy(function(node) {
				if (node.childNodes.length > 0) {
					if (node.isExpanded() == false)
						node.expand();
					return true;
				}
				var vlen = q.trim().length;
				return node.attributes['text'].substr(0, vlen).toLowerCase() == q
						.trim().toLowerCase();
			});
			this.restrictHeight();
			if (this.typeAhead) {
				if (this.keyWord.length > 0) {
					for (var i = 0; i < this.store.getCount(); i++) {
						var object = this.store.getAt(i).data;
						var findObject = this.findValue(object, 0);
						if (findObject != null) {
							this.setValue(findObject);
							this.selectText(this.keyWord.length,
									findObject[this.displayField].length);
							break;
						}
					}
				}
			}
		}
		if (!this.pageSize && this.listType == 'grid') {
			this.store.clearFilter();
			this.store.filter(this.displayField, this.keyWord);
			this.restrictHeight();
			if (this.typeAhead) {
				var record = this.store.getAt(this.store.find(
						this.displayField, this.keyWord));
				if (record || record != undefined) {
					var object = record.data;
					this.setValue(object);
					this.selectText(this.keyWord.length,
							object[this.displayField].length);
				}
			}
		}
		if (!this.listType) {
			this.store.clearFilter();
			this.store.filter(this.displayField, this.keyWord);
			this.restrictHeight();
			if (this.typeAhead) {
				var record = this.store.getAt(this.store.find(
						this.displayField, this.keyWord));
				if (record || record != undefined) {
					var object = record.data;
					this.setValue(object);
					this.selectText(this.keyWord.length,
							object[this.displayField].length);
				}
			}
		}
		this.expand();
	},
	selectPrev : function() {
		if (this.listType && this.listType == 'grid') {
			var record = this.grid.selModel.getSelected();
			if (record) {
				this.grid.selModel.selectPrevious();
			} else {
				this.collapse();
			}
		}
	},
	selectNext : function() {
		if (!this.isExpanded())
			this.onTriggerClick();
		else {
			if (this.listType && this.listType == 'grid') {
				var record = this.grid.selModel.getSelected();
				if (record) {
					this.grid.selModel.selectNext();
				} else {
					this.grid.selModel.selectFirstRow();
				}
			}
		}
	},
	onDestroy : function() {
		if (this.view) {
			this.view.el.removeAllListeners();
			this.view.el.remove();
			this.view.purgeListeners();
		}
		if (this.list) {
			this.list.destroy();
		}
		this.bindStore(null);
		Ext.form.ComboBox.superclass.onDestroy.call(this);
	},
	onBlur : function() {
		if (this.forceSelection == true) {
			if (this.value == null)
				this.setValue(null);
			if (this.value && this.text != this.getEl().dom.value) {
				this.setValue(null);
			}
		}
	},
	createQueryInfo : function(store, options) {
		var q = options.params;
		if (typeof q.start == 'undefined') {
			q.start = 0;
		}
		var queryInfo = {
			listType : 'list',
			entityAlias : null,
			conjunctionType : 'and',
			queryObjectName : this.queryObjectName,
			orderByProps : this.orderByProps
		};
		if (this.pageSize && this.listType == 'grid') {
			queryInfo.pageStart = q.start + 1;
			queryInfo.pageSize = this.pageSize;
			queryInfo.listType = 'page';
		}
		if (this.autoMatchWhenExpand
				&& this.getEl().getValue().trim().length > 0) {
			var fields = [];
			var field = {};
			if (this.matchType == 'likestart')
				field.condition = "likeeic";
			if (this.matchType == 'likeanywhere')
				field.condition = "likeaic";
			field.fieldName = this.displayField;
			field.fieldValueString = this.getEl().getValue().trim();
			fields.push(field);
			queryInfo.fields = fields;
		} else if (this.keyWord.trim() != '') {
			var fields = [];
			var field = {};
			if (this.matchType == 'likestart')
				field.condition = "likeeic";
			if (this.matchType == 'likeanywhere')
				field.condition = "likeaic";
			field.fieldName = this.displayField;
			field.fieldValueString = this.keyWord;
			fields.push(field);
			queryInfo.fields = fields;
		}
		if (this.whereCondition.trim() != '') {
			queryInfo.whereCondition = this.whereCondition;
		}
		store.proxy.DWR = CommonService;
		q.dwrMethod = "findByQueryInit";
		q.dwrArguments = [queryInfo, []];
	},
	onRender : function(ct, position) {
		Gfa.form.ComboBox.superclass.onRender.call(this, ct, position);
		if (this.hiddenName) {
			this.hiddenField = this.el.insertSibling({
				tag : 'input',
				type : 'hidden',
				name : this.hiddenName,
				id : (this.hiddenId || this.hiddenName)
			}, 'before', true);
			this.hiddenField.value = this.hiddenValue !== undefined
					? this.hiddenValue
					: this.value !== undefined ? this.value : '';
			this.el.dom.removeAttribute('name');
		}
		if (Ext.isGecko) {
			this.el.dom.setAttribute('autocomplete', 'off');
		}
		if (!this.lazyInit) {
			this.initList();
		} else {
			this.on('focus', this.initList, this, {
				single : true
			});
		}
		if (!this.editable) {
			this.editable = true;
			this.setEditable(false);
		}
	},
	select : function(obj) {
		if (this.fireEvent('beforeselect', obj, this) != false) {
			this.onSelect(obj);
			this.fireEvent('select', this, obj);
		}
	},
	onSelect : function(obj) {
		this.setValue(obj);
		this.collapse();
	},
	rowSelect : function(grid, rowIndex, e) {
		var obj = grid.getSelectionModel().getSelected().data;
		this.select(obj);
	},
	nodeSelect : function(node) {
		var obj = node.data;
		this.select(obj);
	},
	getValue : function() {
		if (this.valueField) {
			return typeof this.value != 'undefined' ? this.value : '';
		} else {
			return Gfa.form.ComboBox.superclass.getValue.call(this);
		}
	},
	setValue : function(obj) {
		var text, value;
		if (obj && typeof obj == 'object') {
			text = obj[this.displayField];
			value = obj[this.valueField || this.displayField] || '';
		} else {
			text = obj;
			value = obj;
		}
		if (this.hiddenField) {
			this.hiddenField.value = value;
		}
		Gfa.form.ComboBox.superclass.setValue.call(this, text);
		this.text = text;
		this.value = value;
	},
	onViewClick : function() {
		if (this.listType && this.listType == 'grid') {
			var record = this.grid.selModel.getSelected();
			if (record) {
				this.select(record.data);
			}
			this.collapse();
		}
	},
	onResize : function(w, h) {
		Gfa.form.ComboBox.superclass.onResize.apply(this, arguments);
		if (this.list && this.listWidth == null) {
			var lw = Math.max(w, this.minListWidth);
			this.list.setWidth(lw);
			this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
		}
	},
	validateBlur : function() {
		return !this.list || !this.list.isVisible();
	},
	onDestroy : function() {
		if (this.list) {
			this.list.destroy();
		}
		if (this.wrap) {
			this.wrap.remove();
		}
		Gfa.form.ComboBox.superclass.onDestroy.call(this);
	},
	collapseIf : function(e) {
		if (!e.within(this.wrap) && !e.within(this.list)) {
			this.collapse();
		}
	},
	collapse : function() {
		if (!this.isExpanded()) {
			return;
		}
		this.list.hide();
		Ext.getDoc().un('mousewheel', this.collapseIf, this);
		Ext.getDoc().un('mousedown', this.collapseIf, this);
		this.fireEvent('collapse', this);
	},
	expand : function() {
		if (this.isExpanded() || !this.hasFocus) {
			return;
		}
		this.onExpand();
		this.list.alignTo(this.wrap, this.listAlign);
		this.list.show();
		Ext.getDoc().on('mousewheel', this.collapseIf, this);
		Ext.getDoc().on('mousedown', this.collapseIf, this);
		this.fireEvent('expand', this);
	},
	doForce : function() {
	},
	onExpand : function() {
		var doc = Ext.getDoc();
	},
	isExpanded : function() {
		return this.list && this.list.isVisible();
	},
	onTriggerClick : function() {
		if (this.disabled) {
			return;
		}
		if (this.isExpanded()) {
			this.collapse();
		} else {
			this.onFocus({});
			this.expand();
		}
		this.el.focus();
		this.keyWord = '';
		if (this.pageSize && this.listType == 'grid')
			this.store.load({
				params : {
					start : 0,
					limit : this.pageSize
				}
			});
		if (this.listType == 'tree') {
			this.filter.clear();
			this.restrictHeight();
		}
		if (!this.pageSize) {
			this.store.clearFilter();
			this.restrictHeight();
		}
	}
});
Ext.reg('gfaCombobox', Gfa.form.ComboBox);

//解决Ext 排序bug
Ext.override(Ext.grid.ColumnModel, {
	isSortable : function(col){
        if(col > -1 && typeof this.config[col].sortable == "undefined"){
            return this.defaultSortable;
        }
        if(col > -1){
        	return this.config[col].sortable;
        }
        else{
        	return false;
        }
    }
});
//end 解决Ext 排序bug

Ext.namespace("Gfa.data");
Gfa.data.RPCTreeLoader = function(config) {
	Ext.apply(this, config);
	this.addEvents("beforeload", "load", "loadexception");
	Gfa.data.RPCTreeLoader.superclass.constructor.call(this, config);
};
Ext.extend(Gfa.data.RPCTreeLoader, Ext.util.Observable, {
	createNodeConfig : function(attr) {
		if (this.baseAttrs) {
			Ext.applyIf(attr, this.baseAttrs);
		}
		return attr;
	},
	createNode : function(model, parent) {
		var config = this.createNodeConfig(model);
		if (!config.leaf && !config.rpc) {
			config.rpc = parent.attributes.rpc;
		}
		if (!config.leaf) {
			config.loader = parent.attributes.loader;
		}
		return (config.leaf
				? new Ext.tree.TreeNode(config)
				: new Ext.tree.AsyncTreeNode(config));
	},
	load : function(node, callback) {
		if (this.clearOnLoad) {
			while (node.firstChild) {
				node.removeChild(node.firstChild);
			}
		}
		if (this.doPreload(node)) {
			if (typeof callback == "function") {
				callback();
			}
		} else if (node.attributes.rpc) {
			this.requestData(node, callback);
		} else {
			alert("未设置RPC");
		}
	},
	doPreload : function(node) {
		if (node.attributes.children) {
			if (node.childNodes.length < 1) {
				var cs = node.attributes.children;
				node.beginUpdate();
				for (var i = 0, len = cs.length; i < len; i++) {
					var cn = node.appendChild(this.createNode(cs[i]));
					if (this.preloadChildren) {
						this.doPreload(cn);
					}
				}
				node.endUpdate();
			}
			return true;
		} else {
			return false;
		}
	},
	requestData : function(node, treeLoadedcallback) {
		if (this.fireEvent("beforeload", this, node, treeLoadedcallback) !== false) {
			var self = this;
			var opt = {
				callback : function(models) {
					try {
						node.beginUpdate();
						Ext.each(models, function(model) {
							var n = self.createNode(model, node);
							if (n) {
								node.appendChild(n);
							}
						});
						node.endUpdate();
						if (typeof treeLoadedcallback == "function") {
							treeLoadedcallback(this, node);
						}
					} catch (e) {
						alert(e);
					}
				}
			};
			var rpc = node.attributes.rpc;
			rpc.service[rpc.method].apply(rpc.service,
					node.attributes.rpcParams.concat(opt));
		} else {
			if (typeof treeLoadedcallback == "function") {
				treeLoadedcallback();
			}
		}
	}
});
